//
//  NSObject+SCBaseExt.m
//  SCFoundationKit
//
//  Created by Chao Sheng on 2023/10/13.
//

#import "NSObject+SCBaseExt.h"
#import <objc/runtime.h>

@implementation NSObject (SCBaseExt)


- (SEL)sc_selecorBlock:(void (^)(id _Nonnull))block {
    // %p，输出的block内存地址
    NSString *selName = [NSString stringWithFormat:@"sc_selector_%p",block];
    SEL sel = NSSelectorFromString(selName);
    // 将一个新的方法添加到当前类的实现中
    // 实现为 sc_selectorImp
    // v@:@ 表示一个方法的参数和返回值类型
    class_addMethod([self class], sel, (IMP)sc_selectorImp , "v@:@");
    
    objc_setAssociatedObject(self, sel, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    return sel;
}

static void sc_selectorImp(id self, SEL _cmd, id arg) {
    void(^block)(id arg) = objc_getAssociatedObject(self, _cmd);
    if (block) {
        block(arg);
    }
}


- (id)sc_nonull {
    if(self) {
        return self;
    } else {
        return @"";
    }
}

- (BOOL)sc_isEmpty {
    
    if (self == nil) {
        
        return true;
        
    } else if ([self isKindOfClass:[NSNull class]]) {
        
        return true;
        
    } else if ([self isKindOfClass:[NSArray class]]) {
        
        NSArray *array = (NSArray*)self;
        if(array.count > 0) {
            return false;
        } else {
            return true;
        }
        
    } else if ([self isKindOfClass:[NSString class]]) {
        
        NSString *str = (NSString *)self;
        if (str.length > 0) {
            return false;
        }else {
            return true;
        }
    }
    
    return false;
}

@end
